import {ResultCode} from "../network.js";
import {SHA256} from "../../lib/sha256.js";
import popupInfo from "../components/popupInfo.js";
import {setCookie, getCookie, setCookieFromObject, clearCookie} from "../cookies_helper.js";

export default {
    components: {
        'popup-info': popupInfo,
    },
    setup() {
        const userTypes = ['用户', '医生'];
        const userLoginTypes = ['身份证号', '医保号'];
        const doctorLoginTypes = ['医生工号'];
        const router = VueRouter.useRouter();
        const route = VueRouter.useRoute();
        console.log(router)
        // 拿到popup的dom
        const popup = Vue.ref(null);
        const bindUserTypes = Vue.ref(userTypes);
        const bindUserLoginTypes = Vue.ref(userLoginTypes);
        const bindDoctorLoginTypes = Vue.ref(doctorLoginTypes);
        const verifyImg = Vue.ref("");
        const transUserLogin = Vue.ref({
            id: "123",
        })
        const formUserType = Vue.ref(userTypes[0]);
        const formUserLoginType = Vue.ref(userLoginTypes[0]);
        const formDoctorLoginType = Vue.ref(doctorLoginTypes[0]);
        const formUserId = Vue.ref("");
        const formPassword = Vue.ref("");
        const formVerifyCode = Vue.ref("");
        const showUser = Vue.ref(true);
        const showDoctor = Vue.ref(false);
        const remember = Vue.ref(false);

        function showPopup(infoText_ = "提示", titleText_ = "提示") {
            // console.log(popup.value);
            // console.log("showPopup");
            popup.value.onConfirm = () => {
                // console.log("自定义的回调函数");
            };
            popup.value.show(infoText_, titleText_);
        }

        function onVerifyImgClick() {
            axios.get("/verify_code")
                .then(response => {
                    verifyImg.value = response.data.data['img_base64'];
                });
        }

        function onUserTypeChange() {
            if (formUserType.value === userTypes[0]) {
                showUser.value = true;
                showDoctor.value = false;
            } else {
                showUser.value = false;
                showDoctor.value = true;
            }
        }

        Vue.onMounted(() => {
            console.log("onMounted");
            onVerifyImgClick();
            const _remember = getCookie("remember");
            if (remember !== '') {
                remember.value = _remember;
            }
            if (remember.value === 'true') {
                const isUser = getCookie('isUser');
                console.log(`isUser: ${isUser}`);
                const id = getCookie('id');
                console.log(`id: ${id}`);
                const id2 = getCookie('id2');
                console.log(`id2: ${id2}`);
                const password = getCookie('password');
                if (isUser !== '') {
                    if (isUser === 'true') {
                        formUserType.value = userTypes[0];
                        const userLoginType = getCookie("userLoginType");
                        console.log(userLoginTypes[parseInt(userLoginType)]);
                        console.log(parseInt(userLoginType));
                        if (userLoginType !== '') {
                            formUserLoginType.value = userLoginTypes[parseInt(userLoginType)];
                            if (userLoginType === '0') {
                                formUserId.value = id;
                            } else {
                                formUserId.value = id2;
                            }
                        }
                    } else {
                        showUser.value = false;
                        showDoctor.value = true;
                        formUserType.value = userTypes[1];
                        formUserId.value = id;
                    }
                }
                formPassword.value = password;
            }
            console.log("onMounted finished");
        });

        function userLogin(postInfo) {
            axios.post("/user/login", postInfo)
                .then(response => {
                    const responseResult = response.data;
                    console.log("responseResult code: " + responseResult.code);
                    if ((responseResult.code & ResultCode.FAIL) === ResultCode.FAIL) {
                        const failMes = responseResult.message;
                        onVerifyImgClick();
                        showPopup(failMes);
                    } else if (responseResult.code === ResultCode.SUCCESS) {
                        console.log("登录成功");
                        router.push({path: '/user/',});
                    } else {
                        showPopup("连接失败，请检查您的网络连接");
                    }
                });
        }

        function doctorLogin(postInfo) {
            axios.post("/doctor/login", postInfo)
                .then(response => {
                    const responseResult = response.data;
                    console.log("responseResult code: " + responseResult.code);
                    if ((responseResult.code & ResultCode.FAIL) === ResultCode.FAIL) {
                        const failMes = responseResult.message;
                        onVerifyImgClick();
                        showPopup(failMes);
                    } else if (responseResult.code === ResultCode.SUCCESS) {
                        console.log("登录成功");
                        router.push({path: '/doctor/'});
                    } else {
                        showPopup("连接失败，请检查您的网络连接");
                    }
                });
        }

        function submit() {
            console.log("submit");
            let id, id2, isUser, userLoginType;
            if (formUserType.value === userTypes[0]) {
                isUser = true;
                if (formUserLoginType.value === userLoginTypes[0]) {
                    userLoginType = 0;
                    console.log("formUserId: " + formUserId.value);
                    if (formUserId.value === "") {
                        showPopup("请输入" + userLoginTypes[0] + "!");
                        return;
                    }
                    id = formUserId.value;
                    id2 = null;
                } else if (formUserLoginType.value === userLoginTypes[1]) {
                    userLoginType = 1;
                    if (formUserId.value === "") {
                        showPopup("请输入" + userLoginTypes[1] + "!");
                        return;
                    }
                    id = null;
                    id2 = formUserId.value;
                }
            } else {
                isUser = false;
                console.log("formDoctorId: " + formUserId.value);
                if (formUserId.value === "") {
                    showPopup("请输入" + doctorLoginTypes[0] + "!");
                    return;
                }
                id = formUserId.value;
                id2 = null;
            }
            let password = formPassword.value;
            if (password === "") {
                showPopup("请输入密码!");
                return;
            }
            const expireDays = 7;
            clearCookie();
            setCookieFromObject({
                remember: remember.value, isUser, id, id2, password, userLoginType
            }, expireDays);
            let verifyCode = formVerifyCode.value;
            if (verifyCode === "") {
                showPopup("请输入验证码!");
                return;
            }
            const postInfo = {id: id, id2: id2, password: SHA256(password), verify_code: verifyCode};
            if (formUserType.value === userTypes[0]) {
                userLogin(postInfo);
            } else {
                doctorLogin(postInfo);
            }
        }

        function onNewAccountClick() {
            router.push({path: '/new_account/'});
        }

        return {
            popup, showPopup, onVerifyImgClick, submit,
            bindUserTypes, bindUserLoginTypes, bindDoctorLoginTypes,
            verifyImg, transUserLogin, formDoctorLoginType,
            formUserType, formUserLoginType, formPassword, formUserId,
            formVerifyCode, router, route, showUser, onUserTypeChange,
            showDoctor, onNewAccountClick, remember
        }
    },
    template: `
    <div class="container" style="height: 100%;">
    <popup-info
            ref="popup"
    ></popup-info>
    <div style="position: fixed;height: 100%;width: 100%;
    background: url('/images/background/login.png');background-size: 100% 100%;
    left: 0;top: 0;z-index: -1;
    "></div>
    <div class="row" style="height: 13%;"></div>
    <div class="row" style="height: 75%;">
        <div class="col-md-1">
        </div>
        <div class="col-md-4" style="background-color: #90b9d7; height: 100%;">
            <div class="pg-empty-placeholder"
                 style="background: url('/images/logo.png') no-repeat center center; background-size: contain; width: 100%; height: 35%;"></div>
            <h1 class="text-center my-font">系统简介</h1>
            <div class="my-font" style="font-size: 18px;text-indent: 2em;">
                本平台兼容多家医院，患者可以借助平台享受当地医疗资源统合的便捷，
                根据自己的病情和平台的推荐选择适合的就诊医院，目前已基本实现预约挂号、健康咨询、疾病查询、病历查询等功能。
            </div>
        </div>
        <div class="col-md-6 text-center" style="background-color: #EBF2F5; height: 100%;">
            <div class="pg-empty-placeholder" style="height: 8%;"></div>
            <div>
                <h1 class="my-font">复合型医疗问诊系统</h1>
            </div>
            <form @submit.prevent="submit">
                <table class="table" style="margin-top: 50px;border-spacing: 10px 30px;">
                    <tbody>
                    <tr>
                        <td class="my-font" style="font-size: 24px;">用户类型</td>
                        <td colspan="2">
                            <select v-model="formUserType" @change="onUserTypeChange"
                                style="width: 100%; height: 100%; font-size: 24px;" class="my-font text-center">
                                <option v-for="(item, index) in bindUserTypes" :key="index" :value="item">
                                    {{item}}
                                </option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <select v-model="formUserLoginType"
                                    v-show="showUser"
                                    style="height: 100%; font-size: 24px;" class="my-font text-center">
                                <option v-for="(item, index) in bindUserLoginTypes" :key="index" :value="item">
                                    {{item}}
                                </option>
                            </select>
                           <select v-model="formDoctorLoginType"
                                    v-show="showDoctor"
                                    style="height: 100%; font-size: 24px;" class="my-font text-center">
                                <option v-for="(item, index) in bindDoctorLoginTypes" :key="index" :value="item">
                                    {{item}}
                                </option>
                            </select>
                        </td>
                        <td colspan="2">
                            <input type="text" v-model="formUserId"
                                   style="width: 100%; font-size: 24px; padding: 0;" class="my-font">
                        </td>
                    </tr>
                    <tr>
                        <td class="my-font" style="font-size: 24px;">密码</td>
                        <td colspan="2">
                            <input v-model="formPassword"
                                   type="password" style="width: 100%; font-size: 24px; padding: 0;" class="my-font">
                        </td>
                    </tr>
                    <tr>
                        <td class="my-font" style="font-size: 24px;">验证码</td>
                        <td>
                            <input v-model="formVerifyCode"
                                   type="text" style="width: 100%;font-size: 24px; padding: 0;" class="my-font">
                        </td>
                        <td style="width: 40%;">
                            <img style="height: 100%" :src="verifyImg" @click="onVerifyImgClick">
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label class="my-font" style="font-size: 24px;">
                                <input type="checkbox" style="transform: scale3d(2, 2, 2);"
                                    v-model="remember">
                                记住我
                            </label>
                        </td>
                        <td colspan='2'>
                            <div class="pg-empty-placeholder" style="text-align: right; font-size: 24px;
                                cursor: pointer;" @click="onNewAccountClick">
                                没有账号？点此注册
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="3">
                            <button style="width: 100%; background-color: #C7E4FBC2;
                             font-size: 24px; border: none;outline: none;border-radius: 10px;" class="my-font">登录
                            </button>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </form>
        </div>
        <div class="col-md-1">
        </div>
    </div>
<!--    <div>-->
<!--        {{formUserType}}<br>-->
<!--        {{formUserLoginType}}<br>-->
<!--        {{formUserId}}<br>-->
<!--        {{formPassword}}<br>-->
<!--        {{formVerifyCode}}-->
<!--    </div>-->
    </div>`
}